package com.zhike.b2b.sysparam.impl;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;
import javax.sql.DataSource;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import com.zhike.b2b.Query;
import com.zhike.b2b.model.ParamVo;
import com.zhike.b2b.sysparam.IParamService;

@Service
public class ParamService  implements IParamService{

	private static final String CACHE_NAME = "sysParamsCache";
	
	private static final String DATA_CACHE_NAME = "dataParamsCache";

	@Resource
	private CacheManager ehcacheManager;

	private Cache cache ;  
	/**
	 * 根据参数类型和参数值，获取
	 * @param type
	 * @param value
	 * @return
	 */
	public String getDataParam(String type, String value)
	  {
		String key = type+"_"+value;
		cache = ehcacheManager.getCache(DATA_CACHE_NAME);  
		Element element = cache.get(key);
		String name ;
		if(element!=null)
		{
			name = element.getObjectValue().toString();
		}else{
	       String sql = "select param_name from data_parameter where param_value = ? and category_code= ? ";
	       try {
	        name = jt.queryForObject(sql, 
			         new RowMapper<String>() {
						 public String mapRow(ResultSet rs, int rowNum)
							throws SQLException {
							 String val = rs.getString("param_name");
							 return val;
						}},value,type);
		       if(name != null && name.trim().length()>0)
		       {
					element = new Element(key, name);
					cache.put(element);
		       }else
		    	   name = "";
	       } catch (DataAccessException e) {
				name = "";
			}
		}
	    return name;
	  }
	/**
	 * 获取企业会员级别图标信息
	 * @param type
	 * @param value
	 * @return
	 */
	public String getCustLevelLogo(String value)
	  {
		String key = "Cust_Level_"+value;
		cache = ehcacheManager.getCache(DATA_CACHE_NAME);  
		Element element = cache.get(key);
		String name ;
		if(element!=null)
		{
			name = element.getObjectValue().toString();
		}else{
	       String sql = " select LEVEL_LOGO from company_level where LEVEL_ID = ? ";
	       try {
			name = jt.queryForObject(sql, 
		         new RowMapper<String>() {
					 public String mapRow(ResultSet rs, int rowNum)
						throws SQLException {
						 String val = rs.getString("LEVEL_LOGO");
						 return val;
					}},value);
			 if(name != null && name.trim().length()>0)
		     {
				element = new Element(key, name);
				cache.put(element);
		     }else
	    	    name = "";
			} catch (DataAccessException e) {
				name = "";
			}
	   }
	    return name;
	  }
    /**
     * 根据参数名获取参数值，
     * 默认从缓存中获取，如果缓存中没有则查询数据库
     * @param paramName
     * @return String
     */
	public String getParamValue(String paramName)
	{
		cache = ehcacheManager.getCache(CACHE_NAME);  
		Element element = cache.get(paramName);
		String val ;
		if(element!=null)
		{
			val = element.getObjectValue().toString();
		}else{
			val = jt.queryForObject(Query.site_parameter_SEL_SITE_PARAMETER_BY_PARAMETER, new Object[] { paramName },
		         new RowMapper<String>() {
					 public String mapRow(ResultSet rs, int rowNum)
						throws SQLException {
						 String val = rs.getString("param");
						 return val;
					}}
			);
			element = new Element(paramName, val);
			cache.put(element);
		}
		return val;
	}
	
	/**
	 * 查询所有的参数
	 * @return
	 */
    public List<ParamVo> getAllParams()
	{
    	cache = ehcacheManager.getCache(CACHE_NAME);  
		List<ParamVo> lpv = jt.query(Query.site_parameter_GET_PARAMTER_ALL,
				 new RowMapper<ParamVo>() {
					public ParamVo mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						ParamVo pv = new ParamVo();
						pv.setParamName(rs.getString("param_name"));
						pv.setParamValue(rs.getString("param_value"));
						Element element = new Element(pv.getParamName(), pv.getParamValue());
						cache.put(element);
						return pv;
					}
				});
		return lpv;
	}
    /**
     * 更新所有的系统的参数
     * @param paramNames
     * @param paramValues
     */
    public void updateParams(String paramNames,String paramValues)
    {
      cache = ehcacheManager.getCache(CACHE_NAME);  
      final String[] names = paramNames.split("\\#");
      final String[] values =paramValues.split("\\#");
      
      String sql = Query.site_parameter_UPDATE_PARAM_INFO;
	  jt.batchUpdate(sql, new BatchPreparedStatementSetter(){
			public int getBatchSize() {
				return names.length;
			}
          public void setValues(PreparedStatement ps, int i)
					throws SQLException {
        	    ps.setString(1, values[i]);
          	    ps.setString(2, names[i]);
          	    Element element = new Element(names[i], values[i]);
      		    cache.put(element);
			}
		});
    }
    
    /**
     * 更新系统参数
     * @param paramName
     * @param paramValue
     */
    public void updateParam(String paramName,String paramValue)
    {
	      cache = ehcacheManager.getCache(CACHE_NAME);  
	      
	      String sql = Query.site_parameter_UPDATE_PARAM_INFO;
	      jt.update(sql, paramValue,paramName);
	      Element element = new Element(paramName, paramValue);
		  cache.put(element);
    }
    
    protected JdbcTemplate jt;

	protected Logger logger = Logger.getLogger(getClass());
	

	@Resource
	public void setDataSource(DataSource dataSource) {
		jt = new JdbcTemplate(dataSource);
	}
	
}
